package com.meicai.data.engine.local;

import com.meicai.data.core.DataContext;
import com.meicai.data.engine.DataTransform;
import com.meicai.data.pojo.Item;
import com.meicai.data.pojo.SkuItem;
import com.meicai.data.utils.ConfigureUtil;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 加载本地文件，可用于测试模式
 */
public class LocalFileTransform extends DataTransform {

    private SkuItem sku;
    private String filePath;
    private String filename;

    public LocalFileTransform(SkuItem sku, boolean bTest){
        super(bTest);
        this.sku = sku;
        this.filePath = ConfigureUtil.getProperty(bTest ? "file.path.test" : "file.path.online");
//        this.filename = String.format("%s/%s/%s/%s", filePath, sku.cityId, sku.warehouseId, sku.siid, sku.billId);
        this.filename = String.format("%s/%s", filePath, sku.cityId);
    }

    @Override
    public Iterable<String> fetchData() {
        List<String> list = new ArrayList<String>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(new File(this.filename)));
            String data = null;
            while ((data = br.readLine()) != null) {
                list.add(data);
            }
        } catch (FileNotFoundException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        } finally {
            if (br != null)
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return list;
    }

    @Override
    public boolean sinkData(DataContext dataContext) {
      for (Item item : dataContext.itemList) {
            System.out.println(item);
        }
        return true;
    }
}
